<template>
  <div class="material-page">
    <el-card class="header-card" shadow="never">
      <div class="header">
        <div class="title">
          <el-icon style="margin-right:8px; color:#409EFF"><Document /></el-icon>
          <span>退料管理（高朋哲）</span>
        </div>
        <div class="actions">
          <el-button size="small" @click="onAdd">新增</el-button>
          <el-button :loading="loading" type="primary" size="small" @click="loadData" style="margin-left:8px">刷新</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        size="small"
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column prop="materialIds" label="物料ID" width="100" align="center" />
        <el-table-column prop="mayrtName" label="物料名称" width="100" align="center" />
        <el-table-column prop="materialCode" label="物料编码" width="180" show-overflow-tooltip />
        <el-table-column prop="unitName" label="单位" width="100" align="center" />
        <el-table-column prop="workBoss" label="负责人" width="140" show-overflow-tooltip />
        <el-table-column label="类型" width="120" align="center">
          <template #default="scope">
            <el-tag type="success" v-if="Number(scope.row.mTypelId) === 1">良品</el-tag>
            <el-tag type="danger" v-else-if="Number(scope.row.mTypelId) === 2">退料</el-tag>
            <span v-else>{{ scope.row.mTypelId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="specifications" label="规格型号" width="180" show-overflow-tooltip />
        <el-table-column label="数量" width="280" align="center">
          <template #default="scope">
            <div class="nums">
              <el-tag type="info" round>总: {{ scope.row.num }}</el-tag>
              <el-tag type="success" round>良: {{ scope.row.lNum }}</el-tag>
              <el-tag type="danger" round>退: {{ scope.row.tNum }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="massage" label="说明" min-width="220" show-overflow-tooltip />
        <el-table-column prop="beLeft" label="备注" min-width="180" show-overflow-tooltip />
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.state === true" type="success" round>已退货</el-tag>
            <el-tag v-else type="info" round>未退货</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" link type="warning" @click="onChangeState(scope.row)">更改状态</el-button>
            <el-button size="small" link @click="onEdit(scope.row)">编辑</el-button>
            <el-button size="small" link type="danger" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="dialog.visible" :title="dialog.isEdit ? '编辑退料' : '新增退料'" width="640px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" label-width="120px">
        <el-form-item label="物料名称">
          <el-input v-model="formData.mayrtname" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="formData.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="formData.unitName" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="formData.workBoss" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="formData.mTypelId" placeholder="请选择类型" style="width:100%">
            <el-option :value="1" label="良品" />
            <el-option :value="2" label="退料" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="formData.specifications" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="总数量">
          <el-input-number v-model="formData.num" :min="0" style="width:100%" />
        </el-form-item>
        <el-form-item label="良品数量">
          <el-input-number v-model="formData.lNum" :min="0" style="width:100%" />
        </el-form-item>
        <el-form-item label="退料数量">
          <el-input-number v-model="formData.tNum" :min="0" style="width:100%" />
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model="formData.massage" type="textarea" :rows="3" placeholder="请输入说明" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.beLeft" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible=false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'

const loading = ref(false)
const tableData = ref([])
const dialog = reactive({ visible: false, isEdit: false })
const formRef = ref(null)
const formData = reactive({
  materialIds: 0,
  mayrtname: '',
  unitName: '',
  workBoss: '',
  mTypelId: 0,
  specifications: '',
  materialCode: '',
  num: 0,
  lNum: 0,
  tNum: 0,
  massage: '',
  beLeft: ''
})

const BASE = 'http://43.140.208.165:9094/'
const loadData = async () => {
  loading.value = true
  try {
    const res = await axios.get(BASE + 'api/Materi/GetAll')
    if (Array.isArray(res.data)) {
      tableData.value = res.data
    } else if (res.data && Array.isArray(res.data.data)) {
      tableData.value = res.data.data
    } else {
      tableData.value = []
    }
  } catch (e) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

onMounted(loadData)

// 新增
const onAdd = () => {
  dialog.isEdit = false
  dialog.visible = true
  Object.assign(formData, { materialIds: 0, unitName: '', workBoss: '', mTypelId: 0, specifications: '', materialCode: '', num: 0, lNum: 0, tNum: 0, massage: '', beLeft: '' })
}

// 编辑(反填)
const onEdit = async (row) => {
  dialog.isEdit = true
  dialog.visible = true
  try {
    const res = await axios.get(BASE + 'api/Materi/GetById/' + row.materialIds)
    const d = res.data?.data || res.data
    if (d) {
      Object.assign(formData, {
        materialIds: d.materialIds,
        unitName: d.unitName,
        workBoss: d.workBoss,
        mTypelId: d.mTypelId,
        specifications: d.specifications,
        materialCode: d.materialCode,
        num: d.num,
        lNum: d.lNum,
        tNum: d.tNum,
        massage: d.massage,
        beLeft: d.beLeft
      })
    }
  } catch (e) { ElMessage.error('获取详情失败') }
}

// 保存(新增/修改)
const onSubmit = async () => {
  try {
    if (dialog.isEdit) {
      await axios.put(BASE + 'api/Materi/Update/' + formData.materialIds, { ...formData })
    } else {
      await axios.post(BASE + 'api/Materi/Create', { ...formData })
    }
    ElMessage.success('保存成功')
    dialog.visible = false
    loadData()
  } catch (e) { ElMessage.error('保存失败') }
}

// 删除
const onDelete = async (row) => {
  try { await ElMessageBox.confirm('确认删除该记录吗？', '提示', { type: 'warning' }) } catch { return }
  try {
    await axios.delete(BASE + 'api/Materi/Delete/' + row.materialIds)
    ElMessage.success('删除成功')
    loadData()
  } catch (e) { ElMessage.error('删除失败') }
}

// 产品管理（预留）
const onProductManage = (row) => {
  console.log('产品管理:', row)
}

// 更改状态（PATCH）
const onChangeState = async (row) => {
  try { await ElMessageBox.confirm('确定要更改该记录的状态吗？', '提示', { type: 'warning' }) } catch { return }
  try {
    await axios.patch(BASE + 'api/Materi/ChangeState/' + row.materialIds)
    ElMessage.success('状态已更新')
    loadData()
  } catch (e) { ElMessage.error('更新失败') }
}
</script>

<style lang="less" scoped>
.material-page { padding: 20px; }
.header-card { margin-bottom: 12px; }
.header { display: flex; justify-content: space-between; align-items: center; }
.title { display: flex; align-items: center; font-weight: 600; font-size: 16px; }
.nums { display: flex; gap: 8px; justify-content: center; }
:deep(.el-table__row) { height: 36px; }
:deep(.el-table .cell) { line-height: 36px; padding: 4px 8px; }

/* 强制表格背景为白色 */
:deep(.el-table) { background: #fff; }
:deep(.el-table th),
:deep(.el-table td) { background: #fff; }
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) { background: #fafafa; }
</style>


